package com.yuanli.card.res;


import com.yuanli.card.constant.ResponseCode;
import com.yuanli.card.exception.ServiceException;
import com.yuanli.card.utils.JsonMapper;

import java.io.Serializable;

/**
 * 前置响应
 * Created by layne on 2017/6/9.
 */
public class ResponseBean<T> implements Serializable {
    private static final long serialVersionUID = 2253440537602120162L;

    /**
     * 响应码
     */
    private int code;

    /**
     * 响应结果描述
     */
    private String message = "";

    /**
     * 响应数据
     */
    private T data;

    public int getCode() {
        return code;
    }

    public ResponseBean setCode(int code) {
        this.code = code;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public ResponseBean setMessage(String message) {
        this.message = message;
        return this;
    }

    public T getData() {
        return data;
    }

    public ResponseBean<T> setData(T data) {
        this.data = data;
        return this;
    }

    public static ResponseBean success() {
        return new ResponseBean().setCode(0).setMessage("success");
    }

    public static ResponseBean response() {
        return new ResponseBean();
    }

    public static ResponseBean response(ResponseCode code) {
        return new ResponseBean().setCode(code.getCode()).setMessage(code.des());
    }

    /**
     * 服务返回非 0
     *
     * @param msg 提示信息
     */

    public void requireSuccess(String msg) {
        if (code != 0) throw new ServiceException(code, msg);
    }

    /**
     * @param ex
     */
    public void requireSuccess(ServiceException ex) {
        if (code != 0) throw ex;
    }

    /**
     * 需要返回成功
     */
    public void requireSuccess() {
        requireSuccess(message);
    }

    /**
     * @param ex
     */
    public void requireNonNull(ServiceException ex) {
        requireSuccess();
        if (this.getData() == null) throw ex;
    }

    @Override
    public String toString() {
        return JsonMapper.toJsonString(this);
    }

}
